﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yaxunsoft.CasesManagement;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Community.IService;
using FantastPlatform.Framework;
using FantastPlatform.Community.IMode;
using FantastPlatform.Community.Model;
using System.Data.SqlClient;
using System.Configuration;
using System.Threading;

namespace FantastPlatform.Community.UI.Service
{
    public partial class PersonService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginEmployee = Session["User"] as FantastPlatform.Framework.Model.Employee;
            IPersonService personService;
            IBusinessService businessService;
            IHouseHoldService houseHoldeService;
            ICarService carService;
            switch (Action)
            {
                case "AddBusinessPerson":
                    personService = ServiceFactory.CreateService<IPersonService>();
                    HousePerson housePerson = JsonToEntity<HousePerson>(Data);
                    if (!string.IsNullOrEmpty(Request["personStates"]))
                    {
                        housePerson.PersonStates = Request["personStates"];
                    }
                    if (housePerson.Id == 0)
                    {
                        if (housePerson.HouseId != 0)
                        {
                            businessService = ServiceFactory.CreateService<IBusinessService>();
                            IBusiness business = businessService.Get(housePerson.HouseId);
                            IMode.IPerson newPerson = GetPersonByView(housePerson);
                            personService.Create(newPerson);
                            if (business.Persons == null)
                            {
                                business.Persons = new List<IMode.IPerson>();
                            }
                            business.Persons.Add(newPerson);

                            businessService.Update(business);
                        }

                    }
                    else
                    {
                        personService.Update(GetPersonByView(housePerson));

                    }
                    ReturnSuccessMessage("添加成功");

                    break;
                case "AddHousePerson":
                    personService = ServiceFactory.CreateService<IPersonService>();
                    housePerson = JsonToEntity<HousePerson>(Data);
                    if (!string.IsNullOrEmpty(Request["personStates"]))
                    {
                        housePerson.PersonStates = Request["personStates"];
                    }
                    if (housePerson.Id == 0)
                    {
                        if (housePerson.HouseId != 0)
                        {
                            houseHoldeService = ServiceFactory.CreateService<IHouseHoldService>();
                            IHouseHold houseHold = houseHoldeService.Get(housePerson.HouseId);
                            IMode.IPerson newPerson = GetPersonByView(housePerson);
                            personService.Create(newPerson);
                            if (houseHold.Persons == null)
                            {
                                houseHold.Persons = new List<IMode.IPerson>();
                            }
                            houseHold.Persons.Add(newPerson);
                            houseHoldeService.Update(houseHold);
                        }
                    }
                    else
                    {
                        personService.Update(GetPersonByView(housePerson));
                    }


                    ReturnSuccessMessage("添加成功");

                    break;
                case "GetCarsByPerson":
                    personService = ServiceFactory.CreateService<IPersonService>();
                    IMode.IPerson person = personService.Get(Id);
                    if (person != null)
                    {
                        if (person.Cars != null)
                        {
                            object[] objArry = (from c in person.Cars
                                                where c.Enable == true
                                                select new
                                                {
                                                    Id = c.Id,
                                                    Number = c.Number,
                                                    CreateDate = c.CreateDate,
                                                    Enable = c.Enable,
                                                    CarType = c.CarType
                                                }).ToArray();
                            ReturnList(objArry.Length, objArry);
                        }
                    }
                    break;
                case "DeleteCars":
                    carService = ServiceFactory.CreateService<ICarService>();
                    List<int> ids = new List<int>();
                    string[] idArray = Data.Split(',');
                    foreach (string id in idArray)
                    {
                        ids.Add(int.Parse(id));
                    }
                    carService.Delete(ids);
                    ReturnSuccessMessage("移除记录成功");
                    break;
                case "AddCar":
                    if (string.IsNullOrEmpty(Data))
                    {
                        ReturnErrorMessage("添加车辆失败");
                    }
                    else
                    {
                        personService = ServiceFactory.CreateService<IPersonService>();
                        person = personService.Get(Id);
                        carService = ServiceFactory.CreateService<ICarService>();
                        PersonCars CarList = JsonToEntity<PersonCars>(Data);
                        if (person == null)
                        {
                            ReturnErrorMessage("添加车辆失败");
                        }
                        else
                        {
                            foreach (ICar item in CarList.Cars)
                            {
                                item.Person = person;
                                carService = ServiceFactory.CreateService<ICarService>();
                                if (item.Id > 0)
                                {
                                    carService.Update(item);
                                }
                                else
                                {
                                    carService.Create(item);
                                }
                            }
                            ReturnSuccessMessage("添加车辆成功");
                        }
                    }
                    break;
                case "Search":

                    break;
                case "GetPersonType":
                    IPersonTypeService personTypeService = ServiceFactory.CreateService<IPersonTypeService>();
                    int totalCount = 0;
                    IList<IPersonType> list = personTypeService.LoadList(null, Int32.MaxValue, 1, out totalCount);
                    object[] objList = (from t in list
                                        select new { Id = t.Id, Name = t.Name }).ToArray();
                    ReturnList(totalCount, objList);
                    break;
                case "GetStates":
                    IStatesService statesService = ServiceFactory.CreateService<IStatesService>();
                    totalCount = 0;
                    IList<IStates> list2 = statesService.LoadList(null, Int32.MaxValue, 1, out totalCount);
                    objList = (from t in list2
                               select new { Id = t.Id, Name = t.Name }).ToArray();
                    ReturnList(totalCount, objList);
                    break;
                case "GetStatesByPersonId":
                    personService = ServiceFactory.CreateService<IPersonService>();
                    person = personService.Get(Id);
                    string placeType = string.Join(",", (from pt in person.States
                                                         where pt.Enable = true
                                                         select pt.Id.ToString()).ToArray<string>());
                    ReturnSuccessMessage(placeType);
                    break;
                case "GetPersonRelationType":
                    IPersonRelationTypeService personRelationTypeService = ServiceFactory.CreateService<IPersonRelationTypeService>();
                    IList<IPersonRelationType> prtList = personRelationTypeService.LoadList(null, Int32.MaxValue, 1, out totalCount);
                    object[] prtObj = (from t in prtList
                                       select new { Id = t.Id, Name = t.Name }).ToArray();
                    ReturnList(totalCount, prtObj);
                    break;
                case "GetByIdCard":
                    string IdCard = "";
                    if (!string.IsNullOrEmpty(Request["IdCard"]))
                    {
                        IdCard = Request["IdCard"];
                    }
                    FantastPlatform.Community.IMode.IPerson person1 = PersonSearchTools.GetPersonInfoByIdCard(IdCard);
                    if (person1 != null)
                    {
                        ReturnObj(person1);
                    }
                    else
                    {
                        ReturnErrorMessage("查询失败");
                    }
                    break;
                case "Get":
                    personService = ServiceFactory.CreateService<IPersonService>();
                    FantastPlatform.Community.IMode.IPerson person2 = personService.Get(Id);
                    ReturnObj(GetPersonView(person2, "form"));
                    break;
                case "GetPersonByBusiness":
                    businessService = ServiceFactory.CreateService<IBusinessService>();
                    IBusiness business1 = businessService.Get(Id);
                    IList<FantastPlatform.Community.IMode.IPerson> personList = new List<FantastPlatform.Community.IMode.IPerson>();
                    List<HousePerson> businessPersons = new List<HousePerson>();
                    if (business1 != null)
                    {
                        if (business1.Persons != null)
                        {
                            businessPersons = (from p in business1.Persons
                                               where p.Enable == true
                                               select GetPersonView(p, "grid")).ToList();
                        }
                    }
                    ReturnList(personList.Count, businessPersons);
                    break;
                case "GetPersonByBusinessHistry":
                    businessService = ServiceFactory.CreateService<IBusinessService>();
                    business1 = businessService.Get(Id);
                    personList = new List<FantastPlatform.Community.IMode.IPerson>();
                    businessPersons = new List<HousePerson>();
                    if (business1 != null)
                    {
                        if (business1.Persons != null)
                        {
                            businessPersons = (from p in business1.Persons
                                               where p.Enable == false
                                               select GetPersonView(p, "grid")).ToList();
                        }
                    }
                    ReturnList(personList.Count, businessPersons);
                    break;
                case "GetPersonByHouseHold":
                    houseHoldeService = ServiceFactory.CreateService<IHouseHoldService>();
                    IHouseHold houseHold1 = houseHoldeService.Get(Id);
                    personList = new List<FantastPlatform.Community.IMode.IPerson>();
                    businessPersons = new List<HousePerson>();

                    if (houseHold1 != null)
                    {
                        if (houseHold1.Persons != null)
                        {
                            businessPersons = (from p in houseHold1.Persons
                                               where p.Enable == true
                                               select GetPersonView(p, "grid")).ToList<HousePerson>();
                        }


                    }
                    ReturnList(personList.Count, businessPersons);
                    break;
                case "GetPersonByHouseHoldHistry":
                    houseHoldeService = ServiceFactory.CreateService<IHouseHoldService>();
                    houseHold1 = houseHoldeService.Get(Id);
                    personList = new List<FantastPlatform.Community.IMode.IPerson>();
                    businessPersons = new List<HousePerson>();

                    if (houseHold1 != null)
                    {
                        if (houseHold1.Persons != null)
                        {
                            businessPersons = (from p in houseHold1.Persons
                                               where p.Enable == false
                                               select GetPersonView(p, "grid")).ToList<HousePerson>();
                        }


                    }
                    ReturnList(personList.Count, businessPersons);
                    break;
            }
        }

        private static HousePerson GetPersonView(IMode.IPerson p, string type)
        {
            return new HousePerson()
            {
                Id = p.Id,
                QQ = p.QQ,
                Phone = p.Phone,
                Address = p.Address,
                Nation = p.Nation,
                NativePlace = p.NativePlace,
                RegisterAddress = p.RegisterAddress,
                PersonType = type == "form" ? p.PersonType == null ? "" : p.PersonType.Id.ToString() : p.PersonType == null ? "" : p.PersonType.Name,
                Sex = p.Sex,
                Name = p.Name,
                IdCard = p.IdCard,
                Description = p.Description,
                Enable = p.Enable,
                CreateDate = p.CreateDate ,
                CreateDateStr = p.CreateDate.ToString(),
                CarCount = (from n in p.Cars
                            where n.Enable == true
                            select n).Count(),
                PersonRelationType = p.PersonRelationType != null ? p.PersonRelationType.Id.ToString() : "",
                Tel = p.Tel,
                Email = p.Email,
                ModifyDate = p.ModifyDate==null||p.Enable==true?"":p.ModifyDate.Value.ToString(),
                PersonStates = string.Join(",", (from pt in p.States
                                                 where pt.Enable = true
                                                 select pt.Id.ToString()).ToArray<string>())

            };
        }

        private static FantastPlatform.Community.IMode.IPerson GetPersonByView(HousePerson person)
        {
            FantastPlatform.Community.IMode.IPerson personObj = new FantastPlatform.Community.Model.Person()
                   {
                       Id = person.Id,
                       QQ = person.QQ,
                       Phone = person.Phone,
                       Address = person.Address,
                       Nation = person.Nation,
                       NativePlace = person.NativePlace,
                       RegisterAddress = person.RegisterAddress,
                       PersonType = new PersonType() { Id = Int32.Parse(person.PersonType) },
                       Tel = person.Tel,
                       Email = person.Email,
                       Sex = person.Sex,
                       Name = person.Name,
                       IdCard = person.IdCard,
                       Description = person.Description,
                       Enable = person.Enable,
                       CreateDate = person.CreateDate,                      
                       States = GetStates(person.PersonStates)
                   };
            if (!string.IsNullOrEmpty(person.PersonRelationType))
            {
                personObj.PersonRelationType = new PersonRelationType() { Id = Int32.Parse(person.PersonRelationType) };
            }
            return personObj;
        }
        private static IList<IStates> GetStates(string statesStr)
        {
            string[] ptIds;
            IList<IStates> personStates = new List<IStates>();
            if (!string.IsNullOrEmpty(statesStr))
            {
                ptIds = statesStr.Split(',');

                if (ptIds.Length > 0)
                {
                    foreach (string id in ptIds)
                    {
                        personStates.Add(new States() { Id = Int32.Parse(id) });
                    }
                }
            }
            return personStates;
        }

    }
    public class PersonCars
    {
        public List<Car> Cars { get; set; }
    }
    public class HousePerson
    {
        public int Id { get; set; }
        public string QQ { get; set; }
        public string Phone { get; set; }
        public string Address { get; set; }
        public string Nation { get; set; }
        public string NativePlace { get; set; }
        public string RegisterAddress { get; set; }
        public string PersonType { get; set; }
        public string Sex { get; set; }
        public string Name { get; set; }
        public string IdCard { get; set; }
        public string Description { get; set; }
        public string Tel { get; set; }
        public string Email { get; set; }
        public string PersonRelationType { get; set; }
        public int HouseId { get; set; }
        public DateTime? CreateDate { get; set; }
        public string CreateDateStr { get; set; }
        public bool Enable { get; set; }
        public int CarCount { get; set; }
        public string PersonStates { get; set; }
        public string ModifyDate { get; set; }
        public List<Car> Cars { get; set; }
    }

}